package Homework;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author DCSGO
 * @version 1.0
 * 使用ArrayList 完成对对象Car {name, price}的各种操作
 * 1.add:添加单个元素
 * 2.remove:删除指定元素
 * 3.contains:查找元素是否存在
 * 4.size:获取元素个数
 * 5.isEmpty:判断是否为空
 * 6.clear:清空
 * 7.addAll:添加多个元素
 * 8.containsAll:查找多个元素是否都存在
 * 9.removeAll:删除多个元素
 * 使用增强for和迭代器来遍历所有的car，需要重写Car的toString方法
 * Car car = new Car("宝马",400000);
 * Car car2 = new Car("宾利",5000000);
 */

@SuppressWarnings({"all"})
public class Homework02 {
    public static void main(String[] args) {
        ArrayList cars = new ArrayList();
        Car car1 = new Car("宝马", 400000);
        Car car2 = new Car("宾利", 5000000);
        Car car3 = new Car("劳斯莱斯", 111111888);
        cars.add(car1);
        cars.add(car2);
        cars.add(car3);
        System.out.println(cars);
        //[Car{name='宝马', price=400000}, Car{name='宾利', price=5000000}, Car{name='劳斯莱斯', price=111111888}]

        cars.remove(car3);
        System.out.println(cars);
        //[Car{name='宝马', price=400000}, Car{name='宾利', price=5000000}]

        System.out.println(cars.contains(car1));//true
        System.out.println(cars.contains(car3));//false

        System.out.println(cars.size());//2

        System.out.println(cars.isEmpty());//false

        ArrayList cars2 = (ArrayList) cars.clone();
        System.out.println(cars2);
        //[Car{name='宝马', price=400000}, Car{name='宾利', price=5000000}]

        cars.clear();
        System.out.println(cars);//[]

        cars.addAll(cars2);
        System.out.println(cars);
        //[Car{name='宝马', price=400000}, Car{name='宾利', price=5000000}]

        System.out.println(cars.containsAll(cars2));//true
        cars.remove(car1);
        System.out.println(cars.containsAll(cars2));//false

        System.out.println(cars.removeAll(cars2));//true
        System.out.println(cars);//[]

        //foreach
        for (Object obj : cars2) {
            Car car = (Car) obj;
            System.out.println(car);
        }
        //Car{name='宝马', price=400000}
        //Car{name='宾利', price=5000000}

        //迭代器
        Iterator iterator = cars2.iterator();
        while (iterator.hasNext()) {
            Car car = (Car) iterator.next();
            System.out.println(car);
        }
        //Car{name='宝马', price=400000}
        //Car{name='宾利', price=5000000}
    }
}

class Car {
    String name;
    int price;

    public Car(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

